<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 商品表格
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
            </div>
            <el-row>
                <el-col :span="3">
                    <el-button
                            type="primary"
                            icon="el-icon-delete"
                            class="handle-del mr10"
                            @click="delAllSelection"

                    >批量删除</el-button>
                </el-col>
                <el-col :span="4">
                    <el-input v-model="query.username" placeholder="商品名称" class="w-50 m-2"></el-input>
                </el-col>
                <el-col :span="2">
                    <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                </el-col>
                <el-col :span="3">
                    <el-button type="primary"  @click="showAddDialog">添加商品</el-button>
                </el-col>
            </el-row>

            <el-table
                :data="tableData"
                border
                class="table"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column type="index" label="序号" width="70" align="center"></el-table-column>
                <el-table-column label="商品主图">
                    <template #default="scope">
                        <el-image style="width: 50px; height: 50px" :src="scope.row.mainPic" />
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="商品名称"></el-table-column>
                <el-table-column prop="costprice" label="成本价"></el-table-column>
                <el-table-column prop="saleprice" label="售价"></el-table-column>
                <el-table-column label="商品状态">
                    <template #default="scope">
                        <span v-if="scope.row.state==0">
                            上架: {{scope.row.onsaletime}}
                        </span>
                        <span v-else-if="scope.row.state==1">
                            下架: {{scope.row.offsaletime}}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="切换状态">
                    <template #default="scope">
                        <el-button size="mini" @click="changeState(scope.row)">{{scope.row.state==0?'下架':'上架'}}</el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="createtime" label="创建时间"></el-table-column>
                <el-table-column prop="category.name" label="所属类型"></el-table-column>
                <el-table-column prop="brand.name" label="品牌名称"></el-table-column>
                <el-table-column label="操作" width="250" align="center">
                    <template #default="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="showImage(scope.row)"
                        >上传图片</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleDetail(scope.row)"
                        >详情</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    :page-sizes="[3, 5, 8, 10]"
                    layout="total, sizes, prev, pager, next"
                    v-model:current-page="query.current"
                    v-model:page-size="query.size"
                    :total="total"
                    @current-change="getData"
                    @size-change="getData"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑商品信息" v-model="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="商品名称">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="成本价">
                    <el-input-number v-model="form.costprice" :step="5" />
                </el-form-item>
                <el-form-item label="售价">
                    <el-input-number v-model="form.saleprice" :step="5" />
                </el-form-item>
                <el-form-item label="所属类别">
                    <treeselect v-model="form.catId"  :options="catTree"
                                :normalizer="normalizer"
                                 placeholder="选择商品类型"
                                />
                </el-form-item>
                <el-form-item label="品牌">
                    <el-select v-model="form.brandId" class="m-2" placeholder="请选择品牌" size="large">
                        <el-option
                                v-for="item in brandList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                        />
                    </el-select>
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <el-dialog title="上传商品图片" v-model="uploadDialogShow" width="30%">
            <el-upload
                    v-model:file-list="fileList"
                    class="upload-demo"
                    action="http://localhost:8080/up"
                    :headers="{token:token}"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :on-success="handleSuccess"
                    list-type="picture"
                    name="upFile"
            >
                <el-button type="primary">点击上传</el-button>
                <template #tip>
                    <div class="el-upload__tip">
                        jpg/png files with a size less than 500kb
                    </div>
                </template>
            </el-upload>
            <el-button type="primary" @click="saveImage">提交</el-button>
        </el-dialog>


    </div>
</template>

<script>
// import the component
import Treeselect from 'vue3-treeselect'
// import the styles
import 'vue3-treeselect/dist/vue3-treeselect.css'

import common from "@/api/commons";

export default {
    name: "Product",
    components: {Treeselect},
    data() {
        return {
            //用于存放上传过的图片
            fileList: [],
            brandList: [], //品牌列表
            catTree: [],
            query: {
                name: "",
                current: 1,  //当前页
                size: 10   //每页显示的记录数
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            total: 0,  //总记录数
            form: {
                name: '',
                costprice: 0,
                saleprice: 0,
                catId: null,
                brandId: null
            },
            uploadDialogShow: false,
            token: null
        };
    },
    mounted() {
        this.token = localStorage.getItem("token");
        this.getData();
    },
    methods: {
        handleDetail(row){
            this.$router.push({name:'productDetail',params:{productId:row.id}})
        },
        //****************将图片路径更新到表中***************
        saveImage(){
            this.$axios({
                method: 'post',
                url: '/product',
                data: {
                    id: this.productId,
                    mainPic: this.fileList[0].url,
                    resources: JSON.stringify(this.fileList)
                }
            }).then(res=>{
                if (res && res.data.code==200){
                    this.$message.success(res.data.msg || '添加主图和资源图成功');
                    this.uploadDialogShow = false;
                    this.getData();
                }else{
                    this.$message.error(res.data.msg || '添加主图和资源图失败');
                }
            }).catch(error=>{
                this.$message.error(error.message);
            })
        },
        //************弹出上传图片的窗口************
        showImage(row){
            this.fileList = [];
            //存放正在上传图片的商品id
            this.productId = row.id;

            this.$axios({
                method: 'get',
                url: '/product/'+row.id
            }).then(res=>{
                if(res && res.data.code == 200){
                  let resorces = res.data.data.resources;
                  if(resorces){
                      this.fileList = JSON.parse(resorces);
                  }
                  this.uploadDialogShow = true;
                }else{
                  this.$message.error(res.data.msg || '获取商品资源图失败');
                }
            }).catch(error=>{
                this.$message.error(error.message);
            })


        },
        //**************上传成功之后的处理*************
        handleSuccess(res,upFile,upFiles){
            console.log(res,upFile,upFiles);
            this.fileList.push({
                name: upFile.name,
                url: res.data
            })
        },
        handlePreview(file){
            console.log(file)
        },
        handleRemove(uploadFile, uploadFiles){
            console.log(uploadFile, uploadFiles)
        },
        normalizer(node){
            return {
                id: node.id,    //字段名的替换
                label: node.name,
                children: node.children
            }
        },
        //获取商品分类树
        getCatTree(){
            this.$axios({
                method: 'GET',
                url: '/category/tree'
            }).then(res=>{
                if (res && res.data.code==200){
                    this.catTree = res.data.data;
                }else{
                    this.$message.error(res.data.msg || '获取商品分类失败');
                }
            }).catch(error=>{
                this.$message.error(error.message);
            })
        },
        //**************修改状态(上架/下架)************
        changeState(row){
            const data = {
                id: row.id,
            }
            if (row.state==0){
                data.state=1;
                data.offsaletime=common.getDateStr(new Date());
                data.onsaletime=null;
            }else if(row.state==1){
                data.state=0;
                data.onsaletime=common.getDateStr(new Date());
                data.offsaletime=null;
            }
            console.log(data);
            this.$axios({
                method: 'post',
                url: '/product',
                data: data
            }).then(res=>{
                if(res && res.data.code==200){
                    this.$message.success('更新状态成功');
                    this.getData();
                }else{
                    this.$message.error(res.data.msg|| '更新状态失败');
                }
            }).catch(error=>{
                this.$message.error(error.message);
            })
        },
        //显示添加对话框
        showAddDialog(){
            this.form = {
                name:'',
                costprice: 0,
                saleprice: 0,
                catId: null,
                brandId: null
            };
            this.editVisible = true;
            this.getCatTree();
            this.getBrand();
        },
        // 从服务端获取分页数据
        getData() {
            this.$axios({
                method:'post',
                url:'/product/page',
                data: this.query
            }).then(res=>{
                console.log(res);
                if (res && res.data.code == 200){
                    this.tableData = res.data.data.records;
                    this.total = res.data.data.total;
                }
            })

        },
        // 触发搜索按钮
        handleSearch() {
            this.query.current = 1
            this.getData();
        },
        // 删除操作
        handleDelete(row) {
            // 二次确认删除
            this.$confirm("确定要删除吗？", "提示", {
                type: "warning"
            })
            .then(() => {
                //确定删除之后发送删除请求
                this.$axios({
                    method:'delete',
                    url:'/product/'+row.id
                }).then(res=>{
                    if(res.data.code==200){
                        this.$message.success("删除成功");
                        this.getData();
                    }else{
                        this.$message.error("删除失败，请重试");
                    }
                })
            })
            .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            //将data中存储的选中id数组置为空
            this.multipleSelection = [];
            //遍历选中行数组 拿到id放入选中id的数组
            val.forEach(product => {
                this.multipleSelection.push(product.id);
            });
            console.log(this.multipleSelection)
        },
        //批量删除的方法
        delAllSelection() {

            //判断有没有选中项
            if(this.multipleSelection.length==0){
                this.$message.error("没有任何选中项，无法删除");
                return;
            }

            this.$confirm("确定要删除这几项吗？", "提示", {
                type: "warning"
            })
            .then(() => {

                this.$axios({
                    method:'post',
                    url:'/product/batch',
                    data: this.multipleSelection
                }).then(res=>{
                    if(res.data.code==200){
                        this.$message.success("删除成功");
                        this.getData();
                    }else{
                        this.$message.error("删除失败，请重试");
                    }
                })
            })
            .catch(() => {});
        },
        // 编辑操作
        handleEdit(index, row) {
            this.getCatTree();
            this.getBrand();
            this.form = Object.assign({},row);
            // this.form.catId = row.category.id
            console.log('编辑回显的商品信息-----',this.form);
            this.editVisible = true;
        },
        // 保存编辑
        saveEdit() {
            //发送添加或修改请求
            this.$axios({
                method:'post',
                url: '/product',
                data: this.form
            }).then(res=>{
                if(res.data.code == 200){
                    this.getData();
                    this.editVisible = false;
                    this.$message.success(`操作成功`);
                }else{
                    this.$message.error(`操作失败，请重试`);
                }
            })
           
        },
        //查询品牌列表
        getBrand(){
            this.$axios({
                method: 'get',
                url: '/dicdetail/getByType/productBrand'
            }).then(res=>{
                if (res && res.data.code == 200){
                    this.brandList = res.data.data
                }
            }).catch(error=>{
                this.$message.error(error.message);
            })
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
